#!/bin/bash -e
# Parameters
#!/bin/bash

GS_PASSWORD=Aops@123

OG_SUBNET="172.11.0.0/24"
IPPREFIX=172.11.0.
START=101
HOST_PORT=5432
LOCAL_PORT=5434

MASTER_NODENAME=opengauss_master
SLAVE_NODENAME=opengauss_slave

nums_of_slave=1

docker stop ${MASTER_NODENAME} 2>/dev/null ||:
docker rm ${MASTER_NODENAME} 2>/dev/null ||:
for ((i=1;i<=nums_of_slave;i++)) ; do
	docker stop ${SLAVE_NODENAME}${i} 2>/dev/null ||:
	docker rm ${SLAVE_NODENAME}${i} 2>/dev/null ||:
done
docker network rm opengaussnetwork 2>/dev/null

docker network create --subnet=$OG_SUBNET opengaussnetwork \
|| {
  echo ""
  echo "ERROR: OpenGauss Database Network was NOT successfully created."
  echo "HINT: opengaussnetwork Maybe Already Exsist Please Execute 'docker network rm opengaussnetwork' "
  exit 1
}
echo "OpenGauss Database Network Created."

conninfo=""
for ((i=1;i<=nums_of_slave;i++))
do
	ip=`expr $START + $i`
	hport=`expr $HOST_PORT + 1000 \* $i`
	lport=`expr $LOCAL_PORT + 1000 \* $i`
	conninfo+="replconninfo$i = 'localhost=$IPPREFIX$START localport=$LOCAL_PORT localservice=$HOST_PORT remotehost=$IPPREFIX$ip remoteport=$lport remoteservice=$hport'\n"
done
echo -e $conninfo


for ((i=0;i<=nums_of_slave;i++))
do
	if [ $i == 0 ]; then
		hport=$HOST_PORT
		lport=$LOCOL_PORT
		ip=$START
		nodeName=$MASTER_NODENAME
		conn=$conninfo
		role="primary"
	else
		hport=`expr $HOST_PORT + 1000 \* $i`
		lport=`expr $LOCAL_PORT + 1000 \* $i`
		ip=`expr $START + $i`
		nodeName=$SLAVE_NODENAME$i
		conn="replconninfo1 = 'localhost=$IPPREFIX$ip localport=$lport localservice=$hport remotehost=$IPPREFIX$START remoteport=$LOCAL_PORT remoteservice=$HOST_PORT'\n"
		role="standby"
	fi
	docker run --network opengaussnetwork --ip $IPPREFIX$ip --privileged=true \
	--name $nodeName -h $nodeName -p $hport:$hport -d \
	-e GS_PORT=$hport \
	-e OG_SUBNET=$OG_SUBNET \
	-e GS_PASSWORD=$GS_PASSWORD \
	-e NODE_NAME=$nodeName \
	-e REPL_CONN_INFO="$conn" \
	-v $GS_DATADIR/$nodeName:/var/lib/opengauss \
	hub.oepkgs.net/a-ops/opengauss:3.0.0 -M $role \
	|| {
	  echo ""
	  echo "ERROR: OpenGauss Database $role  Docker Container was NOT successfully created."
	  exit 1
	}
	echo "OpenGauss Database $role Docker Container created."
	sleep 30s
done
